package com.example.glxt1.config.Interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.glxt1.common.Constants;
//import com.example.glxt1.entity.User;
import com.example.glxt1.exeception.ServiceException;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.PostConstruct;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class TokenInterceptor implements HandlerInterceptor {
//    @Resource
//    private IUserService userService;

    private static TokenInterceptor tokenInterceptor; //

    /**
     * 重新构造一个方法
     * 通过 @PreDestroy 或 @PostContruct 实现初始化和销毁bean之前进行的操作
     * @PostContruct 这个注解就是在springboot启动前就加载
     */
    @PostConstruct
    public void init() {
        tokenInterceptor=this;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("**************  token拦截器生效");
     String  token=request.getHeader("token");
//     如果不是直接映射到方法直接通过
     if(!(handler instanceof HandlerMethod)){
         return true;
     }
//     执行验证，验证token是否为空
     if(StrUtil.isBlank(token)){
         throw new ServiceException(Constants.CODE_401,"无token请重新登录");
     }
//     获取token中的userid，
        String userId;
     try {
         userId= JWT.decode(token).getAudience().get(0);
         System.out.println("***********"+userId);
     }catch (JWTDecodeException e){
         throw new ServiceException(Constants.CODE_401,"token验证失败");
     }
//     查询用户，是否存在
//     User user=getUser(Integer.parseInt(userId));
//     if(user==null){
//         throw new ServiceException(Constants.CODE_401,"用户不存在请重新登陆");
//     }
//     用户密码加签验证 token
//        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(user.getPassword())).build();
//     try {
//         jwtVerifier.verify(token);
//     }catch (JWTVerificationException e){
//         throw new ServiceException(Constants.CODE_401,"token加签验证失败");
//     }
     return  true;
    }

//    public User getUser(Integer id){
//        return  tokenInterceptor.userService.getById(id);
//    }
}
